package com.hollycrm.hollysqm.analyzer.seg.impl;


import java.util.List;

import org.ansj.domain.Term;
import org.ansj.library.UserDefineLibrary;
import org.ansj.splitWord.analysis.ToAnalysis;
import org.ansj.util.FilterModifWord;
import org.apache.commons.lang.StringUtils;

import com.hollycrm.hollysqm.analyzer.seg.AbstractSegment;
import com.hollycrm.hollysqm.analyzer.seg.Segment;

/**
 * ansj分词器
 * Created by zhaihw on 2016/1/28.
 */
public class AnsjWordSegmenter extends AbstractSegment {
    private AnsjWordSegmenter () {}
    private static AnsjWordSegmenter segmenter = new AnsjWordSegmenter();
    public static Segment getInstance() {
        return segmenter;
    }
    /**
     * 分词，不包含词性
     *
     * @param sentence 待分词的句子
     * @return 返回以空格隔开的词串
     */
    @Override
    public String processWithoutNature(String sentence) {
        if(StringUtils.isEmpty(sentence))return null;
        List<Term> terms = ToAnalysis.parse(sentence);
        if(terms == null || terms.isEmpty())return null;
        StringBuilder builder = new StringBuilder();
        for(Term term:terms)
            builder.append(term.getName()).append(" ");
        return builder.toString();
    }

    /**
     * 分词，包含词性
     *
     * @param sentence 待分词的句子
     * @return
     */
    @Override
    public String processWithNature(String sentence) {
        if(StringUtils.isEmpty(sentence))return null;
        List<Term> terms = ToAnalysis.parse(sentence);
        if(terms == null || terms.isEmpty())return null;
        StringBuilder builder = new StringBuilder();
        for(Term term:terms)
            builder.append(term.getName()).append("/").append(term.getNatureStr()).append(" ");
        return builder.toString();
    }


    /**
     * 加载用户词典
     *
     * @param nature 词性
     * @param word   词语
     */
    @Override
    public void loadUserWord(String nature, String word) {
        super.loadUserWord(nature, word);
        if(StringUtils.isNotEmpty(word))
            UserDefineLibrary.insertWord(word,nature,1);
    }

    /**
     * 加载用户词典
     *
     * @param nature 词性
     * @param words  词语
     */
    @Override
    public void loadUserWord(String nature, String... words) {
        super.loadUserWord(nature, words);
        if(words!=null && words.length>0)
            for(String word:words) {
                if(StringUtils.isNotEmpty(word))
                    UserDefineLibrary.insertWord(word, nature, 1);
            }
    }

    /**
     * 加载停用词
     *
     * @param stopWords 停用词
     * @return 加载成功数量
     */
    @Override
    public void loadStopWord(String... stopWords) {
        super.loadStopWord(stopWords);
        if(stopWords!=null && stopWords.length>0)
                FilterModifWord.insertStopWord(stopWords);
    }
}
